﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using StandXunYouWeb.Model;
using StandXunYouWeb.Utility;
using System.Drawing;
using System.Drawing.Imaging;

namespace StandXunYouWeb.Controllers
{
    public class AccountController : Controller
    {

        private readonly ILogger _logger;

        private readonly BaseRequest _Req;

        public AccountController(ILogger<AccountController> logger, BaseRequest Req)
        {
            _logger = logger;
            _Req = Req;
        }

        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(string userName, string verCode)
        {
            try
            {
                List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
                list.Add(new KeyValuePair<string, string>("userId", userName));

                var code = HttpContext.Session.GetString("VerCode");
                if (!verCode.Equals(code, StringComparison.OrdinalIgnoreCase))
                {
                    return Ok(BaseState.CreateInstance(BaseState.RequestField, "验证码错误"));
                }

                //获取用户数据
                var result = await _Req.Post("/api/Login/", list);
                var bJson = JsonConvert.DeserializeObject<BaseState>(result); //将返回来得数据实例化

                if (bJson.Code == 200)
                {
                    var model = JsonConvert.DeserializeObject<Users>(bJson.Data.ToString());

                    var token = AuthorManage.GetToken(model.UserName, model.Id);
                    Response.Cookies.Append("token", token);

                    return Ok(BaseState.CreateInstance(200, bJson.Msg));
                }
                else
                {
                    return Ok(BaseState.CreateInstance(BaseState.RequestError, bJson.Msg));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, "用户登录失败");
            }
            return Ok(BaseState.CreateInstance(BaseState.RequestError, "请求服务器失败，请稍后重试"));
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public IActionResult LogOut()
        {
            Response.Cookies.Delete("token");
            return RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// 绘制验证码
        /// </summary>
        /// <returns></returns>
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult GetVerifyCode()
        {
            string code = CommonHelpers.GenerateRandom(4);
            HttpContext.Session.SetString("VerCode", code);
            var img = DrawImage(code);
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, ImageFormat.Jpeg);

                return File(ms.ToArray(), "image/jpeg");
            }
        }

        public static Bitmap DrawImage(string code)
        {
            Color[] colors = {
                Color.Red, Color.OrangeRed,Color.SaddleBrown,
                Color.LimeGreen,Color.Green,Color.MediumAquamarine,
                Color.Blue,Color.MediumOrchid,Color.Black,
                Color.DarkBlue,Color.Orange,Color.Brown,
                Color.DarkCyan,Color.Purple
            };
            string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
            Random random = new Random();
            // 创建一个 Bitmap 图片类型对象
            Bitmap bitmap = new Bitmap(code.Length * 23, 32);
            // 创建一个图形画笔
            Graphics graphics = Graphics.FromImage(bitmap);
            // 将图片背景填充成白色
            graphics.Clear(Color.White);
            // 绘制验证码噪点
            for (int i = 0; i < random.Next(60, 80); i++)
            {
                int pointX = random.Next(bitmap.Width);
                int pointY = random.Next(bitmap.Height);
                graphics.DrawLine(new Pen(Color.LightGray, 1), pointX, pointY, pointX + 1, pointY);
            }
            // 绘制随机线条 1 条
            graphics.DrawLine(
                    new Pen(colors[random.Next(colors.Length)], random.Next(3)),
                    new Point(
                        random.Next(bitmap.Width),
                        random.Next(bitmap.Height)),
                    new Point(random.Next(bitmap.Width),
                    random.Next(bitmap.Height)));
            // 绘制验证码
            for (int i = 0; i < code.Length; i++)
            {
                graphics.DrawString(
                    code.Substring(i, 1),
                    new System.Drawing.Font(fonts[random.Next(fonts.Length)], 18, FontStyle.Bold),
                    new SolidBrush(colors[random.Next(colors.Length)]),
                    16 * i + 1,
                    random.Next(0, 5)
                    );
            }
            // 绘制验证码噪点
            for (int i = 0; i < random.Next(30, 50); i++)
            {
                int pointX = random.Next(bitmap.Width);
                int pointY = random.Next(bitmap.Height);
                graphics.DrawLine(new Pen(colors[random.Next(colors.Length)], 1), pointX, pointY, pointX, pointY + 1);
            }
            // 绘制随机线条 1 条
            graphics.DrawLine(
                    new Pen(colors[random.Next(colors.Length)], random.Next(3)),
                    new Point(
                        random.Next(bitmap.Width),
                        random.Next(bitmap.Height)),
                    new Point(random.Next(bitmap.Width),
                    random.Next(bitmap.Height)));
            return bitmap;
        }

    }
}
